import { defineStore } from 'pinia';
import { getToken, removeToken, setToken } from '../utils/token-utils';
import type { UserInfoState } from './interface';
import {ElMessage} from 'element-plus'
import {staticRoutes} from '@/router/routes'
import { reqLogin } from '@/api/user';


/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfoStore = defineStore('userInfo', {
	state: (): UserInfoState => ({
    token: getToken() as string,
    name: '',
    avatar: '',
    menuRoutes: []
  }),

	actions: {
    async login (username: string, password: string) {
        //login是一个异步函数,将来调用这个函数的时候,会确认是否成功,所以默认login返回成功promise,如果在login中发生失败,则应该返回失败的promise
     try{
      const result=await reqLogin({username,password})
      // 设置token本地存储
      setToken(result.token)
      // 把token放在state中
      this.token=result.token
     }catch(e){
      return Promise.reject(e)
     }
    },

    getInfo () {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          this.name = 'admin'
          this.avatar = 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif'
          this.menuRoutes = staticRoutes
          resolve({name: this.name, avatar: this.avatar, token: this.token})
        }, 1000)
      })
    },

    reset () {
      // 删除local中保存的token
      removeToken()
      // 提交重置用户信息的mutation
      this.token = ''
      this.name = ''
      this.avatar = ''
    },
	},
});
